package org.example.lotterysystem.service.impl;

import jakarta.annotation.Resource;
import org.example.lotterysystem.common.domain.dto.CreatePrizeDTO;
import org.example.lotterysystem.common.domain.dto.PageDTO;
import org.example.lotterysystem.common.domain.vo.FindPrizeListVO;
import org.example.lotterysystem.mapper.PrizeMapper;
import org.example.lotterysystem.mapper.dataobject.PrizeDO;
import org.example.lotterysystem.service.PictureService;
import org.example.lotterysystem.service.PrizeService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PrizeServiceImpl implements PrizeService {
    @Resource
    PrizeMapper prizeMapper;

    @Resource
    PictureService pictureService;

    @Override
    public Long createPrize(CreatePrizeDTO createPrizeDTO, MultipartFile picFile) {
        //上传图片
        String picture = pictureService.savePicture(picFile);
        //存入数据库
        PrizeDO prizeDO=new PrizeDO();

        prizeDO.setName(createPrizeDTO.getPrizeName());
        prizeDO.setImageUrl(picture);
        prizeDO.setDescription(createPrizeDTO.getDescription());
        prizeDO.setPrice(createPrizeDTO.getPrice());

        prizeMapper.insert(prizeDO);

        return prizeDO.getId();
    }

    @Override
    public FindPrizeListVO findPrizeList(PageDTO pageDTO) {
        FindPrizeListVO findPrizeListVO=new FindPrizeListVO();

        //获取总数
        int total=prizeMapper.count();

        //获取当前列表
        List<PrizeDO> prizeDOList=prizeMapper.selectPrizeList(pageDTO.offset(),pageDTO.getPageSize());

        findPrizeListVO.setTotal(total);
        findPrizeListVO.setRecords(
                prizeDOList.stream()
                        .map(prizeDTO -> {
                            FindPrizeListVO.PrizeInfo prizeInfo = new FindPrizeListVO.PrizeInfo();
                            prizeInfo.setPrizeId(prizeDTO.getId());
                            prizeInfo.setPrizeName(prizeDTO.getName());
                            prizeInfo.setDescription(prizeDTO.getDescription());
                            prizeInfo.setImageUrl(prizeDTO.getImageUrl());
                            prizeInfo.setPrice(prizeDTO.getPrice());
                            return prizeInfo;
                        }).collect(Collectors.toList())
        );

        return findPrizeListVO;
    }
}
